/** @format */

import axios from 'axios';
import { getToken } from './storage';
import { saveToken } from '@/utils/storage';

// 请求基地址
export const baseURL = '/api';

// 创建 axios 实例
const request = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

// 请求拦截器
request.interceptors.request.use(
  function (config) {
    const token = getToken();
    if (token) {
      (config.headers as any).Authorization = `Bearer ${token}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  function (response) {
    return response.data;
  },
  async function (error) {
    console.dir(error);
    if (error.response.status === 401) {
      const res = await axios({
        url: '/api/sys/login',
        method: 'post',
        data: { mobile: '13800000002', password: '123456' },
      });
      saveToken(res.data.data);
      return request(error.config);
    }
    return Promise.reject(error);
  }
);

// 导出 axios 实例
export default request;
